package conn

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/utils"
)

var DB *gorm.DB

func init() {

	//"user:password@/dbname?charset=utf8&parseTime=True&loc=Local"
	connString := "root:Mysql(123456)@tcp(172.29.49.15:3306)/go_demo?charset=utf8mb4&parseTime=True&loc=Asia%2FShanghai"
	DB, _ = gorm.Open(mysql.Open(connString), &gorm.Config{})
	callInjector(DB)
	databaseName := DB.Migrator().CurrentDatabase()
	fmt.Println("current schema: " + databaseName)

}

func GetDB() *gorm.DB {
	return DB
}

var injectors []func(db *gorm.DB)

// RegisterInjector 注册回调
func RegisterInjector(f func(*gorm.DB)) {
	injectors = append(injectors, f)
}

// 执行回调
func callInjector(db *gorm.DB) {
	for _, v := range injectors {
		v(db)
	}
	fmt.Println("执行回调finish")
}

// SetupTableModel 自动初始化表结构
func SetupTableModel(model interface{}) {
	// AutoMigrate 自动迁移
	_ = DB.AutoMigrate(model) //这里会自动创建表
	if !DB.Migrator().HasTable(model) {
		err := DB.Set("gorm:table_options", "ENGINE=InnoDB").Migrator().CreateTable(model)
		if err != nil {
			fmt.Println("创建表失败 -- " + err.Error())
		} else {
			fmt.Println("创建表成功 -- " + utils.ToString(model))
		}
	} else {
		fmt.Println("数据表已存在，无需创建")
	}

}
